import { getEnhancedFamilyTree, searchFamilyTree, addChild, addSpouse, getMemberDetail, getMemberSpouses, getMemberSiblings } from '../../api/tree';
import { formatDate } from '../../utils/util';
import { getImageUrl } from '../../utils/image';

Page({
  data: {
    treeData: null,
    timelineData: [],
    selectedMember: null,
    loadingTree: true,
    currentMemberId: null,
    viewMode: 'tree',
    zoomLevel: 80, // 降低初始缩放比例，以便看到更多节点
    zoomScale: 0.8, // 对应的缩放比例
    touchStartX: 0,
    touchStartY: 0,
    searchKeyword: '',
    searchResults: [],
    showAddForm: false,
    addFormType: 'child', // 'child' or 'spouse'
    addFormData: {
      name: '',
      gender: 'M',
      birthDate: '',
      nativePlace: '',
      currentAddress: '',
    },
    showDebug: false, // 是否显示调试信息
    forceRefresh: 0 // 强制刷新标志
  },

  onLoad: function(options) {
    // 添加调试模式
    if (options.debug === '1') {
      this.setData({ showDebug: true });
    }
    
    // 延迟加载，确保页面先渲染
    setTimeout(() => {
      this.loadEnhancedFamilyTree();
    }, 300);
  },

  // 加载增强版家族树数据
  async loadEnhancedFamilyTree() {
    wx.showLoading({ title: '加载家族树...' });
    try {
      this.setData({ loadingTree: true });
      
      // 使用增强版API获取更完整的家族树数据
      const res = await getEnhancedFamilyTree({
        generations: 5,
        includeSiblings: true
      });
      
      console.log('增强版家族树原始数据:', res);
      
      if (res.code === 0) {
        // 检查树数据结构
        console.log('树节点数量:', res.data.tree ? res.data.tree.length : 0);
        console.log('树结构:', JSON.stringify(res.data.tree, null, 2));
        
        // 检查是否有centerMemberId
        console.log('中心成员ID:', res.data.centerMemberId);
        
        // 处理树节点数据
        const treeData = this.processTreeData(res.data.tree || []);
        const timelineData = this.generateTimelineData(res.data.tree || []);
        
        console.log('处理后的树数据:', treeData);
        
        // 确保有树数据
        if (treeData && treeData.length > 0) {
          // 递归打印树结构，帮助调试
          this.printTreeStructure(treeData[0]);
          
          this.setData({
            treeData: treeData,
            timelineData: timelineData,
            currentMemberId: res.data.centerMemberId,
            loadingTree: false
          });
          
          // 强制刷新，确保视图更新
          setTimeout(() => {
            this.setData({
              forceRefresh: Date.now()
            });
          }, 500);
        } else {
          console.error('处理后没有树数据');
          wx.showToast({
            title: '家族树数据处理失败',
            icon: 'none'
          });
          this.setData({ loadingTree: false });
        }
      } else {
        // 如果增强版API失败，尝试使用原始API
        this.loadFamilyTree();
      }
    } catch (error) {
      console.error('加载增强版家族树出错', error);
      // 如果增强版API出错，尝试使用原始API
      this.loadFamilyTree();
    } finally {
      wx.hideLoading();
    }
  },

  // 原始加载家族树数据方法（作为备用）
  async loadFamilyTree() {
    wx.showLoading({ title: '加载家族树...' });
    try {
      this.setData({ loadingTree: true });
      const res = await getFamilyTree();
      console.log('家族树原始数据:', res);
      
      if (res.code === 0) {
        // 检查树数据结构
        console.log('树节点数量:', res.data.tree ? res.data.tree.length : 0);
        console.log('树结构:', JSON.stringify(res.data.tree, null, 2));
        
        // 检查是否有centerMemberId
        console.log('中心成员ID:', res.data.centerMemberId);
        
        // 处理树节点数据
        const treeData = this.processTreeData(res.data.tree || []);
        const timelineData = this.generateTimelineData(res.data.tree || []);
        
        console.log('处理后的树数据:', treeData);
        
        // 确保有树数据
        if (treeData && treeData.length > 0) {
          // 递归打印树结构，帮助调试
          this.printTreeStructure(treeData[0]);
          
          this.setData({
            treeData: treeData,
            timelineData: timelineData,
            currentMemberId: res.data.centerMemberId,
            loadingTree: false
          });
          
          // 强制刷新，确保视图更新
          setTimeout(() => {
            this.setData({
              forceRefresh: Date.now()
            });
          }, 500);
        } else {
          console.error('处理后没有树数据');
          wx.showToast({
            title: '家族树数据处理失败',
            icon: 'none'
          });
          this.setData({ loadingTree: false });
        }
      } else {
        wx.showToast({
          title: res.msg || '加载家族树失败',
          icon: 'none'
        });
        this.setData({ loadingTree: false });
      }
    } catch (error) {
      console.error('加载家族树出错', error);
      wx.showToast({
        title: '加载家族树出错，请稍后重试',
        icon: 'none'
      });
      this.setData({ loadingTree: false });
    } finally {
      wx.hideLoading();
    }
  },
  
  // 递归打印树结构，帮助调试
  printTreeStructure(node, level = 0) {
    if (!node) return;
    
    const indent = '  '.repeat(level);
    console.log(`${indent}节点: ${node.name} (ID: ${node.id})`);
    
    if (node.spouse) {
      console.log(`${indent}配偶: ${node.spouse.name} (ID: ${node.spouse.id})`);
    }
    
    if (node.siblings && node.siblings.length > 0) {
      console.log(`${indent}兄弟姐妹数量: ${node.siblings.length}`);
      node.siblings.forEach((sibling, index) => {
        console.log(`${indent}  第 ${index + 1} 个兄弟姐妹: ${sibling.name} (ID: ${sibling.id})`);
      });
    }
    
    if (node.children && node.children.length > 0) {
      console.log(`${indent}子节点数量: ${node.children.length}`);
      node.children.forEach((child, index) => {
        console.log(`${indent}第 ${index + 1} 个子节点:`);
        this.printTreeStructure(child, level + 1);
      });
    } else {
      console.log(`${indent}没有子节点`);
    }
  },

  // 处理树节点数据，添加出生年份、逝世年份等信息
  processTreeData(treeNodes) {
    if (!treeNodes || treeNodes.length === 0) {
      console.log('没有树节点数据');
      return [];
    }
    
    const app = getApp();
    const imgBase = app.globalData.imgBase || '';
    
    const processNode = (node) => {
      if (!node) return null;
      
      // 创建节点的副本，避免直接修改原始数据
      const processedNode = { ...node };
      
      // 添加出生年和逝世年
      if (processedNode.birth_date) {
        const birthDate = new Date(processedNode.birth_date);
        processedNode.birthYear = birthDate.getFullYear();
        processedNode.birthDate = formatDate(birthDate);
      }
      
      if (processedNode.death_date) {
        const deathDate = new Date(processedNode.death_date);
        processedNode.deathYear = deathDate.getFullYear();
        processedNode.deathDate = formatDate(deathDate);
      }
      
      // 处理照片路径
      if (processedNode.photo) {
        processedNode.photo = getImageUrl(processedNode.photo, imgBase);
      }
      
      // 处理配偶节点
      if (processedNode.spouse_id && processedNode.spouse_name) {
        processedNode.spouse = {
          id: processedNode.spouse_id,
          name: processedNode.spouse_name,
          gender: processedNode.spouse_gender || 'F', // 默认女性
          birth_date: processedNode.spouse_birth_date,
          death_date: processedNode.spouse_death_date,
          photo: processedNode.spouse_photo
        };
        
        // 处理配偶的日期
        if (processedNode.spouse.birth_date) {
          const spouseBirthDate = new Date(processedNode.spouse.birth_date);
          processedNode.spouse.birthYear = spouseBirthDate.getFullYear();
          processedNode.spouse.birthDate = formatDate(spouseBirthDate);
        }
        
        if (processedNode.spouse.death_date) {
          const spouseDeathDate = new Date(processedNode.spouse.death_date);
          processedNode.spouse.deathYear = spouseDeathDate.getFullYear();
          processedNode.spouse.deathDate = formatDate(spouseDeathDate);
        }
        
        // 处理配偶照片
        if (processedNode.spouse.photo) {
          processedNode.spouse.photo = getImageUrl(processedNode.spouse.photo, imgBase);
        }
      }
      
      // 处理兄弟姐妹节点
      if (processedNode.siblings && processedNode.siblings.length > 0) {
        processedNode.siblings = processedNode.siblings.map(sibling => {
          const processedSibling = { ...sibling };
          
          // 处理兄弟姐妹的日期
          if (processedSibling.birth_date) {
            const siblingBirthDate = new Date(processedSibling.birth_date);
            processedSibling.birthYear = siblingBirthDate.getFullYear();
            processedSibling.birthDate = formatDate(siblingBirthDate);
          }
          
          if (processedSibling.death_date) {
            const siblingDeathDate = new Date(processedSibling.death_date);
            processedSibling.deathYear = siblingDeathDate.getFullYear();
            processedSibling.deathDate = formatDate(siblingDeathDate);
          }
          
          // 处理兄弟姐妹照片
          if (processedSibling.photo) {
            processedSibling.photo = getImageUrl(processedSibling.photo, imgBase);
          }
          
          return processedSibling;
        });
      }
      
      // 递归处理子节点
      if (processedNode.children && processedNode.children.length > 0) {
        console.log(`处理 ${processedNode.name} (ID: ${processedNode.id}) 的 ${processedNode.children.length} 个子节点`);
        
        // 确保每个子节点都被正确处理
        const processedChildren = [];
        processedNode.children.forEach((child, index) => {
          console.log(`处理第 ${index + 1} 个子节点: ${child.name} (ID: ${child.id})`);
          const processedChild = processNode(child);
          if (processedChild) {
            processedChildren.push(processedChild);
          } else {
            console.warn(`子节点 ${index} 处理失败`);
          }
        });
        
        processedNode.children = processedChildren;
        console.log(`${processedNode.name} 处理后有 ${processedNode.children.length} 个子节点`);
      } else {
        console.log(`${processedNode.name} (ID: ${processedNode.id}) 没有子节点`);
      }
      
      return processedNode;
    };
    
    console.log(`开始处理 ${treeNodes.length} 个根节点`);
    const result = [];
    
    treeNodes.forEach((node, index) => {
      console.log(`处理第 ${index + 1} 个根节点: ${node.name} (ID: ${node.id})`);
      const processedNode = processNode(node);
      if (processedNode) {
        result.push(processedNode);
      }
    });
    
    console.log(`处理完成，共有 ${result.length} 个根节点`);
    return result;
  },

  // 生成时间线数据
  generateTimelineData(treeNodes) {
    const timelineData = [];
    
    const extractMembers = (node) => {
      if (!node) return;
      
      // 添加当前节点
      timelineData.push({
        id: node.id,
        name: node.name,
        gender: node.gender,
        birthDate: node.birthDate,
        deathDate: node.deathDate,
        birthYear: node.birthYear,
        generation: node.generation
      });
      
      // 添加配偶
      if (node.spouse) {
        timelineData.push({
          id: node.spouse.id,
          name: node.spouse.name,
          gender: node.spouse.gender,
          birthDate: node.spouse.birthDate,
          deathDate: node.spouse.deathDate,
          birthYear: node.spouse.birthYear,
          generation: node.generation
        });
      }
      
      // 添加兄弟姐妹
      if (node.siblings && node.siblings.length > 0) {
        node.siblings.forEach(sibling => {
          timelineData.push({
            id: sibling.id,
            name: sibling.name,
            gender: sibling.gender,
            birthDate: sibling.birthDate,
            deathDate: sibling.deathDate,
            birthYear: sibling.birthYear,
            generation: node.generation
          });
        });
      }
      
      // 递归处理子节点
      if (node.children && node.children.length > 0) {
        node.children.forEach(child => extractMembers(child));
      }
    };
    
    // 从根节点开始递归
    if (treeNodes && treeNodes.length > 0) {
      extractMembers(treeNodes[0]);
    }
    
    // 按出生年份排序
    return timelineData.sort((a, b) => {
      if (!a.birthYear) return 1;
      if (!b.birthYear) return -1;
      return a.birthYear - b.birthYear;
    });
  },

  // 切换视图模式
  switchViewMode(e) {
    const mode = e.currentTarget.dataset.mode;
    this.setData({ viewMode: mode });
  },

  // 缩放控制
  zoomIn() {
    let zoomLevel = this.data.zoomLevel + 20;
    if (zoomLevel > 200) zoomLevel = 200;
    
    this.setData({
      zoomLevel: zoomLevel,
      zoomScale: zoomLevel / 100
    });
  },

  zoomOut() {
    let zoomLevel = this.data.zoomLevel - 20;
    if (zoomLevel < 50) zoomLevel = 50;
    
    this.setData({
      zoomLevel: zoomLevel,
      zoomScale: zoomLevel / 100
    });
  },

  // 触摸事件处理
  touchStart(e) {
    if (e.touches.length === 1) {
      this.setData({
        touchStartX: e.touches[0].clientX,
        touchStartY: e.touches[0].clientY
      });
    }
  },

  touchMove(e) {
    // 可以在这里实现拖动功能
  },

  touchEnd(e) {
    // 触摸结束，可以处理惯性滚动等
  },

  // 搜索相关
  onSearchInput(e) {
    this.setData({ searchKeyword: e.detail.value });
  },

  async onSearch() {
    const keyword = this.data.searchKeyword;
    if (!keyword) return;
    
    wx.showLoading({ title: '搜索中...' });
    try {
      const res = await searchFamilyTree({ name: keyword });
      
      if (res.code === 0 && res.data.success) {
        // 处理搜索结果
        const searchResults = res.data.searchResults || [];
        const treeData = this.processTreeData(res.data.tree);
        const timelineData = this.generateTimelineData(res.data.tree);
        
        this.setData({
          searchResults,
          treeData,
          timelineData,
          currentMemberId: res.data.centerMemberId
        });
        
        if (searchResults.length === 0) {
          wx.showToast({
            title: '未找到匹配的成员',
            icon: 'none'
          });
        }
      } else {
        wx.showToast({
          title: res.data.message || '搜索失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('搜索出错', error);
      wx.showToast({
        title: '搜索出错，请稍后重试',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  // 选择成员
  selectMember(e) {
    const member = e.currentTarget.dataset.member;
    this.setData({ selectedMember: member });
    
    // 如果是兄弟姐妹，可以查看以他为中心的树
    if (member.id !== this.data.currentMemberId) {
      wx.showActionSheet({
        itemList: ['查看详情', '以此成员为中心查看家族树'],
        success: (res) => {
          if (res.tapIndex === 0) {
            // 查看详情
            this.viewMemberDetail({ currentTarget: { dataset: { id: member.id } } });
          } else if (res.tapIndex === 1) {
            // 以此成员为中心查看家族树
            this.loadEnhancedFamilyTree({ memberId: member.id });
          }
        }
      });
    }
  },

  // 关闭成员详情
  closeDetail() {
    this.setData({ selectedMember: null });
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 什么都不做，仅阻止冒泡
  },

  // 查看成员详情
  viewMemberDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/memberdetail/index?id=${id}`
    });
  },

  // 显示添加子女表单
  showAddChildForm(e) {
    const parentId = e.currentTarget.dataset.id;
    this.setData({
      showAddForm: true,
      addFormType: 'child',
      addFormData: {
        parentId,
        name: '',
        gender: 'M',
        birthDate: '',
        nativePlace: '',
        currentAddress: ''
      }
    });
  },

  // 显示添加配偶表单
  showAddSpouseForm(e) {
    const memberId = e.currentTarget.dataset.id;
    this.setData({
      showAddForm: true,
      addFormType: 'spouse',
      addFormData: {
        memberId,
        name: '',
        gender: this.data.selectedMember.gender === 'M' ? 'F' : 'M', // 默认选择相反性别
        birthDate: '',
        nativePlace: '',
        currentAddress: ''
      }
    });
  },

  // 关闭添加表单
  closeAddForm() {
    this.setData({ showAddForm: false });
  },

  // 提交添加表单
  async submitAddForm(e) {
    const formValues = e.detail.value;
    const formType = this.data.addFormType;
    const formData = {
      ...this.data.addFormData,
      ...formValues
    };
    
    // 参数验证
    if (!formData.name) {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      });
      return;
    }
    
    wx.showLoading({ title: '提交中...' });
    try {
      let res = null;
      if (formType === 'child') {
        res = await addChild({
          parentId: formData.parentId,
          name: formData.name,
          gender: formData.gender,
          birthDate: formData.birthDate,
          nativePlace: formData.nativePlace,
          currentAddress: formData.currentAddress
        });
      } else {
        res = await addSpouse({
          memberId: formData.memberId,
          name: formData.name,
          gender: formData.gender,
          birthDate: formData.birthDate,
          nativePlace: formData.nativePlace,
          currentAddress: formData.currentAddress
        });
      }
      
      if (res.code === 0) {
        wx.showToast({
          title: '已提交审核',
          icon: 'success'
        });
        this.setData({
          showAddForm: false,
          addFormData: {
            name: '',
            gender: 'M',
            birthDate: '',
            nativePlace: '',
            currentAddress: ''
          }
        });
      } else {
        wx.showToast({
          title: res.msg || '提交失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('提交出错', error);
      wx.showToast({
        title: '提交出错，请稍后重试',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  // 添加调试功能，帮助用户查看树形结构
  debugShowAllNodes() {
    // 递归计算节点数量
    const countNodes = (node) => {
      if (!node) return 0;
      let count = 1; // 当前节点
      
      if (node.spouse) count++; // 配偶节点
      
      if (node.siblings && node.siblings.length > 0) {
        node.siblings.forEach(sibling => {
          count += countNodes(sibling);
        });
      }

      if (node.children && node.children.length > 0) {
        node.children.forEach(child => {
          count += countNodes(child);
        });
      }
      return count;
    };
    
    // 计算总节点数
    let totalNodes = 0;
    if (this.data.treeData && this.data.treeData.length > 0) {
      this.data.treeData.forEach(node => {
        totalNodes += countNodes(node);
      });
    }
    
    // 显示节点统计信息
    wx.showModal({
      title: '家族树节点统计',
      content: `共有 ${totalNodes} 个成员节点`,
      showCancel: false
    });
    
    // 打印树形结构
    console.log('完整树形结构:', JSON.stringify(this.data.treeData, null, 2));
  },
  
  // 强制重新加载树
  forceReloadTree() {
    wx.showLoading({ title: '重新加载中...' });
    
    // 清空当前数据
    this.setData({
      treeData: null,
      timelineData: [],
      loadingTree: true
    });
    
    // 延迟重新加载
    setTimeout(() => {
      this.loadEnhancedFamilyTree();
    }, 500);
  },
  
  // 调整缩放以适应所有节点
  fitAllNodes() {
    this.setData({
      zoomLevel: 60,
      zoomScale: 0.6
    });
    wx.showToast({
      title: '已缩小显示全部节点',
      icon: 'none'
    });
  },

  // 页面相关生命周期
  onShareAppMessage() {
    return {
      title: '家族树',
      path: '/pages/tree/index'
    };
  }
}); 